package com.colin.ui.component;

import com.colin.util.CommonUtils;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.util.ui.JBUI;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.function.Consumer;

public class MergeDialogView extends JDialog {
    private JTextField mergeNameField;
    private JTextField mergeBranchField;
    private JTextField targetBranchField;
    private JButton okButton;
    private JButton cancelButton;
    private final Consumer<List<String>> consumer;

    public MergeDialogView(Frame frame, Consumer<List<String>> consumer) {
        super(frame, "merge request", true);
        setupUI();
        setupActions();
        pack();
        this.consumer = consumer;
    }

    private void setupUI() {
        mergeNameField = new JTextField(20);
        mergeBranchField = new JTextField(10);
        targetBranchField = new JTextField(10);
        mergeBranchField.setText(CommonUtils.getCurrentGitBranch(ProjectManager.getInstance().getOpenProjects()[0].getBasePath()));
        targetBranchField.setText("master");

        okButton = new JButton("确定");
        cancelButton = new JButton("取消");
        JLabel arrowLabel = new JLabel("== >", SwingConstants.CENTER);

        JPanel fieldsPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = JBUI.insets(4);

        gbc.gridx = 0;
        gbc.gridy = 0;
        fieldsPanel.add(new JLabel("合并名称:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 3;
        fieldsPanel.add(mergeNameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        fieldsPanel.add(new JLabel("合并分支:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        fieldsPanel.add(mergeBranchField, gbc);

        gbc.gridx = 2;
        gbc.gridy = 1;
        fieldsPanel.add(arrowLabel, gbc);

        gbc.gridx = 3;
        gbc.gridy = 1;
        fieldsPanel.add(targetBranchField, gbc);

        JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonsPanel.add(okButton);
        buttonsPanel.add(cancelButton);

        getContentPane().add(fieldsPanel, BorderLayout.CENTER);
        getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
    }

    private void setupActions() {
        okButton.addActionListener(e -> {
            consumer.accept(List.of(mergeNameField.getText(),
                    mergeBranchField.getText(),
                    targetBranchField.getText()));
            dispose(); // 关闭对话框
        });

        cancelButton.addActionListener(e -> {
            dispose(); // 关闭对话框
        });
    }
}
